var express = require('express');
var router = express.Router();

const Form = require('../models/form')
const FormData = require('../models/formData')

var formController = require('../controllers/form')

router.get('/forms', async (req, res, next) => {
	console.log('get forms');
	let conditions = {};
	let tenant = req.query.tenant;
	if (tenant) conditions.tenant = tenant;
	let forms = await Form.find({...conditions}, "-content -content_data -content_parse -fields -add_fields").exec();

	res.json( {status: 200, result: forms} )
})

router.put('/forms/:id', async (req, res, next) => {
	console.log('save form');
	let id = req.params.id;
	let data = req.body;
	let newForm = await Form.findOneAndUpdate({_id: id}, {...data}).exec();

	res.json( {status: 200, result: {form_name: newForm.form_name, form_desc: newForm.form_desc, _id: newForm._id}} )
})

router.post('/forms', async (req, res, next) => {
	console.log('create new form');
	let data = req.body;
	let newForm = await new Form(data).save();

	res.json( {status: 200, result: newForm} )
})

router.delete('/forms/:id', async (req, res, next) => {
	console.log('delete form');
	let id = req.params.id;
	await Form.deleteOne({_id: id});

	res.json( {status: 200, result: 'success'} )
})

module.exports = router